package com.agile.leetcode.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/12/23 10:50
 */
public class GetDemo {
    public static void main(String[] args) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 构建对象
            httpClient = HttpClients.createDefault();
            //2、创建HttpGet，声明get请求
            HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
            // 发送请求
            httpResponse = httpClient.execute(httpGet);
            // 判断状态码
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 拿到响应对象
                HttpEntity entity = httpResponse.getEntity();
                String string = EntityUtils.toString(entity, "utf-8");
                System.out.println(string);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 5、关闭资源
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
